package api.storage;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import api.Person;

/**
 * @author Ann Raboschuk
 */
public class DataStorageExcel implements IDataStorage
{
   private String filename;
   
   public DataStorageExcel(String filename)
   {
      this.filename = filename;
   }

   @Override
   public List<Person> load() throws Exception
   {
      Workbook workbook = Workbook.getWorkbook(new File(filename));
      Sheet sheet = workbook.getSheet(0);
      Field[] fields = Class.forName("api.Person").getDeclaredFields();
      List<Person> list = new ArrayList<Person>();
      for (int row = 0; row < sheet.getRows(); row++)
      {
         Person person = new Person();
         for (int i=0; i<fields.length; i++)
         {
            Field field = fields[i];
            field.setAccessible(true);
            String value = sheet.getCell(i,row).getContents();
            Class<?> fieldType = fields[i].getType();
            if (Modifier.isStatic(field.getModifiers()))
               continue;
            if (fieldType.equals(String.class))
               field.set(person, fieldType.cast(value));
            else
            {
               if (fieldType.equals(Character.class))
                  field.set(person, value.charAt(0));
               else
               {            	              	  
            	  Method method = fieldType.getMethod("valueOf", String.class);            	  
                  field.set(person, method.invoke(null, value));
               }
            }
         }
         list.add(person);
      }
      workbook.close();
      return list;
   }

   @Override
   public void save(List<Person> records) throws Exception
   {
      WritableWorkbook workbook = Workbook.createWorkbook(new File(filename));
      WritableSheet sheet = workbook.createSheet("Persons", 0);
      Field[] fields = Class.forName("api.Person").getDeclaredFields();
      for (int i=0; i<records.size(); i++)
      {
         for (int j=0; j<fields.length; j++)
         {
            if (!Modifier.isStatic(fields[j].getModifiers()))
            {
               fields[j].setAccessible(true);
               sheet.addCell(new Label(j, i, fields[j].get(records.get(i)).toString())); 
            }
         }
      }
      workbook.write(); 
      workbook.close();
   }
}
